package com.zzy.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzy.common.core.redis.RedisCache;
import com.zzy.common.utils.guanmai.GuanmaiCommon;
import com.zzy.system.domain.*;
import com.zzy.system.mapper.OutStockSheetOrderDetailBatchMapper;
import com.zzy.system.mapper.OutStockSheetOrderDetailMapper;
import com.zzy.system.mapper.OutStockSheetOrderMapper;
import com.zzy.system.service.IOutStockSheetOrderDetailBatchService;
import com.zzy.system.service.IOutStockSheetOrderDetailService;
import com.zzy.system.service.IOutStockSheetOrderService;
import com.zzy.system.service.ISaleOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OutStockSheetOrderServiceImpl extends ServiceImpl<OutStockSheetOrderMapper, OutStockSheetOrder> implements IOutStockSheetOrderService {
    private static final Logger log = LoggerFactory.getLogger(OutStockSheetOrderServiceImpl.class);

    // 注入 RedisCache 对象
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IOutStockSheetOrderDetailService iOutStockSheetOrderDetailService;
    @Autowired
    private IOutStockSheetOrderDetailBatchService outStockSheetOrderDetailBatchService;
    @Autowired
    private OutStockSheetOrderDetailMapper outStockSheetOrderDetailMapper;
    @Autowired
    private OutStockSheetOrderDetailBatchMapper outStockSheetOrderDetailBatchMapper;
    // 定义日期时间格式，与要转换的字符串格式相匹配
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    // 注入配置文件中的观麦令牌在 Redis 中的键名
    @Value("${api.guanmaiTokenKey}")
    private String guanmaiTokenKey;
    // 注入配置文件中的观麦接口 URL


    //请求观麦 获取订单集合
    @Override
    @Transactional
    public String getOutStckSheetOrderList(Integer status, String startDate, String endDate, Integer offset, Integer limit, Integer queryType) throws Exception {
        List<OutStockSheetOrder> allOutStockSheetOrderList=new ArrayList<>();
        limit=100;
        while (true) {
            Map<String, Object> paramMap = new HashMap<>();
            // 获取今天的日期
            LocalDate today = LocalDate.now();
            // 获取7天前的日期
            LocalDate sevenDaysAgo = today.minusDays(30);

            // 将日期格式化为yyyy-MM-dd格式的字符串
            String startDateStr = sevenDaysAgo.toString();
            String endDateStr = today.toString();

            // 设置开始日期参数
            paramMap.put("start_date", startDate);
            // 设置截止日期参数
            paramMap.put("end_date", endDate);
            // 订单状态 2 已出库
            paramMap.put("status", status);
            // 设置分页offset参数（默认值为0，可按需不传该参数或者修改值）
            paramMap.put("offset", offset);
            // 设置分页limit参数（默认值为100，取值范围<=100，可按需不传该参数或者修改值）
            paramMap.put("limit", limit);
            paramMap.put("type", 2);

            //请求观麦 获取订单列表
            String reponse = GuanmaiCommon.sendRequestGet(paramMap, "/v1/api/stock/out_stock_sheet/list/2.0");
            JSONObject reponseJson = JSONObject.parseObject(reponse);
            if (reponseJson.getInteger("code") == 1002) {
                redisCache.deleteObject(guanmaiTokenKey);
                GuanmaiCommon.getGuanmaiToken();
                continue;
            }
            if (reponseJson.get("code").toString().equals("0")) {
                JSONArray jsonArray = reponseJson.getJSONArray("data");
                if (jsonArray != null) {
                    // 将当前页的数据解析并添加到总的结果列表中
                    List<OutStockSheetOrder> outStockSheetOrderList = jsonArray.toJavaList(OutStockSheetOrder.class);
                    allOutStockSheetOrderList.addAll(outStockSheetOrderList);
                    // 如果返回的数据条数等于每页显示的数量，说明可能还有更多数据，继续查询下一页
                    if (jsonArray.size() == limit) {
                        offset += limit; // 页码增加，指向下一页
                        continue;
                    } else {
                        // 如果返回的数据条数小于每页显示的数量，说明已经查询完所有数据，结束循环
                        break;
                    }
                }
            } else {
                // 如果接口返回的code不是0，表示请求出现问题，这里可以根据实际情况进行错误处理
                System.out.println("请求出现问题，错误信息：" + reponseJson.get("msg"));
                break;
            }

        }

        int batchSize = 100;
        for (int i = 0; i < allOutStockSheetOrderList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, allOutStockSheetOrderList.size());
            List<OutStockSheetOrder> batchList = allOutStockSheetOrderList.subList(i, endIndex);
            // 这里可以将batchList用于实际的saveBatch操作或者其他处理
            System.out.println("当前批次数据量: " + batchList.size());
            batchInsert(batchList, batchSize);
        }

        System.out.println(allOutStockSheetOrderList);
        return "";
    }


    public void   senGauanMaiOrderDetail(String orderId) throws Exception {
        Map<String, Object> paramMap = new HashMap<>();
        // 设置查询order_id
        paramMap.put("out_stock_sheet_id", orderId);
        //请求观麦 获取订单列表
        String reponse = GuanmaiCommon.sendRequestGet(paramMap, "/v1/api/stock/out_stock_sheet/get/1.1");
        JSONObject reponseJson = JSONObject.parseObject(reponse);
        if (reponseJson.getInteger("code") == 1002) {
            redisCache.deleteObject(guanmaiTokenKey);
            GuanmaiCommon.getGuanmaiToken();
        }
        if (reponseJson.get("code").toString().equals("0")) {
            JSONObject jsonObject = reponseJson.getJSONObject("data");
            OutStockSheetOrder saleOrder = JSON.parseObject(jsonObject.toString(), OutStockSheetOrder.class);
            if (saleOrder != null && !saleOrder.getDetails().isEmpty()) {
                QueryWrapper<OutStockSheetOrderDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("out_stock_sheet_id", orderId);
                outStockSheetOrderDetailMapper.delete(queryWrapper);
                QueryWrapper<OutStockSheetOrderDetailBatch> outStockSheetOrderDetailBatchQueryWrapper = new QueryWrapper<>();
                outStockSheetOrderDetailBatchQueryWrapper.eq("out_stock_sheet_id", orderId);
                outStockSheetOrderDetailBatchMapper.delete(outStockSheetOrderDetailBatchQueryWrapper);
                // 使用forEach方法遍历Details集合并设置purchaseSheetId属性
                saleOrder.getDetails().forEach(detail -> detail.setOutStockSheetId(orderId));
                for(OutStockSheetOrderDetail orderDetail : saleOrder.getDetails()) {
                    Integer detailId=iOutStockSheetOrderDetailService.saveOutStockSheetOrderDetails(orderDetail);
                    if (detailId != null&&detailId > 0) {
                        if(!orderDetail.getOutStockSheetOrderDetailBatchList().isEmpty()){
                            orderDetail.getOutStockSheetOrderDetailBatchList().forEach(batch ->
                                        batch.setDetailId(detailId.toString()));
                            orderDetail.getOutStockSheetOrderDetailBatchList().forEach(batch ->
                                    batch.setOutStockSheetId(orderId));
                            outStockSheetOrderDetailBatchService.saveOutStockSheetOrderDetailBatch(orderDetail.getOutStockSheetOrderDetailBatchList());
                        }

                    }
                }

            }

            System.out.println(saleOrder);

        }
    }
    public void getSaleOrderInfo(String orderId) throws Exception {
        Map<String, Object> paramMap = new HashMap<>();
        // 设置查询order_id
        paramMap.put("order_id", orderId);
        //请求观麦 获取订单列表
        String reponse = GuanmaiCommon.sendRequestGet(paramMap, "/v1/api/order/get/1.1");
        JSONObject reponseJson = JSONObject.parseObject(reponse);
        if (reponseJson.getInteger("code") == 1002) {
            redisCache.deleteObject(guanmaiTokenKey);
            GuanmaiCommon.getGuanmaiToken();
        }
        if (reponseJson.get("code").toString().equals("0")) {
            JSONObject jsonObject = reponseJson.getJSONObject("data");
            SaleOrder saleOrder = JSON.parseObject(jsonObject.toString(), SaleOrder.class);
            if (saleOrder != null&&saleOrder.getOutOrderId()!=null&&!saleOrder.getOutOrderId().equals("")) {
                UpdateWrapper<OutStockSheetOrder> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("out_stock_sheet_id", orderId).set("out_order_id", saleOrder.getOutOrderId());
                this.update(null, updateWrapper);
            }

            System.out.println(saleOrder);

        }
    }
    public void batchInsert(List<OutStockSheetOrder> outStockSheetOrderList, int batchSize) throws Exception {
        // 提前查询数据库中已存在的Orderid集合
        List<String> existingSheetIds = getExistingOrderSheetIds(outStockSheetOrderList);
        // 过滤掉已存在的orderId对应的记录
        List<OutStockSheetOrder> filteredList = filterExistingRecords(outStockSheetOrderList, existingSheetIds);
        // 按批次插入过滤后的数据
        int driverIndex = 0; // 用于记录当前取司机信息的索引位置
        boolean reverseDirection = false; // 用于标记是否反向取（从头往前取）
        for (int i = 0; i < filteredList.size(); i += batchSize) {
            List<SaleOrderDriver> saleOrderDriverList = new ArrayList<>();
            int endIndex = Math.min(i + batchSize, filteredList.size());
            List<OutStockSheetOrder> batchList = filteredList.subList(i, endIndex);
            System.out.println("当前批次数据量: " + batchList.size());
            this.saveOrUpdateBatch(batchList);
            for (OutStockSheetOrder order : batchList) {
                    //循环查询采购入库单的详情
                    senGauanMaiOrderDetail(order.getOutStockSheetId());
            }
        }
    }

    private List<String> getExistingOrderSheetIds(List<OutStockSheetOrder> outStockSheetOrders) {
        if (outStockSheetOrders == null || outStockSheetOrders.isEmpty()) {
            return new ArrayList<>();
        }

        List<String> sheetIdList = new ArrayList<>();
        for (OutStockSheetOrder order : outStockSheetOrders) {
            sheetIdList.add(order.getOutStockSheetId());
        }

        QueryWrapper<OutStockSheetOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("out_stock_sheet_id").in("out_stock_sheet_id", sheetIdList);

        return this.getBaseMapper().selectObjs(queryWrapper).stream()
                .map(obj -> (String) obj).collect(Collectors.toList());
    }

    private List<OutStockSheetOrder> filterExistingRecords(List<OutStockSheetOrder> saleOrders, List<String> existingSheetIds) {
        List<OutStockSheetOrder> saleOrderList = new ArrayList<>();
        for (OutStockSheetOrder order : saleOrders) {
            if (!existingSheetIds.contains(order.getOutStockSheetId())) {
                saleOrderList.add(order);
            }
        }
        return saleOrderList;
    }


}